package com.oristand.sqlmonitor.config;

import com.oristand.sqlmonitor.entity.DbEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.oristand.sqlmonitor.config.DynamicDataSourceUtil.getDataSource;

/**
 * 动态数据源
 *
 * @author wangmeng
 * @since 2023/7/5
 */
@Component
public class DynamicDatasource extends AbstractRoutingDataSource {

    // 连接池属性
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

   public Map<Object, Object> targetDataSources;


    @Override
    protected String determineCurrentLookupKey() {
        return getDataSource();
    }

    @Override
    public void afterPropertiesSet() {
        registerDynamicDataSources();
    }


    /**
     * 从数据库读取租户的DB配置,并动态注入Spring容器
     */
    private void registerDynamicDataSources() {
        // 模拟租户的DB配置 //可以从数据库读取 也可以配置文件配置
        DbEntity entity = new DbEntity();
        entity.setPort("3306");
        entity.setDatabaseName("sql-monitor");
        entity.setPassword(password);
        entity.setUsername(username);
        entity.setJdbcUrl(url);
        entity.setDriverName(driverClassName);
         targetDataSources = new LinkedHashMap<>();
        DataSource dataSource = createDataSource(entity);
        targetDataSources.put(entity.getDatabaseName(),dataSource );
        //将创建的map对象set到targetDataSources
        setTargetDataSources(targetDataSources);
        //设置默认数据源
        setDefaultTargetDataSource(dataSource);
        //将targetDataSources放入resolvedDataSources
        super.afterPropertiesSet();
    }

    /**
     * 根据DataSource创建bean
     */
    public void addDataSourceBeans(List<DbEntity> entities) {
        for (DbEntity entity : entities) {
            String beanKey = entity.getDatabaseName();
            targetDataSources.put(beanKey, createDataSource(entity));
        }
        //将创建的map对象set到targetDataSources
        setTargetDataSources(targetDataSources);
        //将targetDataSources放入resolvedDataSources
        super.afterPropertiesSet();
    }


    public static DataSource createDataSource(DbEntity dbEntity) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dbEntity.getDriverName());
        dataSource.setUrl(dbEntity.getJdbcUrl() + "/" + dbEntity.getDatabaseName() + "?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&useLegacyDatetimeCode=false&useAffectedRows=true&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true");
        dataSource.setUsername(dbEntity.getUsername());
        dataSource.setPassword(dbEntity.getPassword());
        return dataSource;
    }
}
